package cn.wsalix.finance.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.anlaser.service.impl.SimpleServiceImpl;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.finance.entity.CardWaste;
import cn.wsalix.finance.entity.CreditCard;
import cn.wsalix.finance.entity.Customer;
import cn.wsalix.finance.form.CardWasteForm;
import cn.wsalix.finance.repository.CardWasteRepository;
import cn.wsalix.finance.service.CardWasteService;
import cn.wsalix.finance.service.CreditCardService;
import cn.wsalix.finance.service.CustomerService;

@Service("cardWasteService")
public class CardWasteServiceImpl extends
		SimpleServiceImpl<CardWasteForm, CardWasteRepository, CardWaste>
		implements CardWasteService {
	@Autowired
	private CardWasteRepository cardWasteRepository;
	@Autowired
	private CreditCardService creditCardService;
	@Autowired
	private CustomerService customerService;

	@Override
	public String module() {
		return "/finance/card_waste";
	}

	@Override
	public CardWasteRepository getRepository() {
		return cardWasteRepository;
	}

	@Override
	public Class<CardWaste> getEntityClazz() {
		return CardWaste.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(CardWasteForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getCustomerId() != null && form.getCustomerId() != 0) {
			filters.put("customerId", new SearchFilter("customerId",
					Operator.EQ, form.getCustomerId()));
		}
		if (form.getCardId() != null && form.getCardId() != 0) {
			filters.put("cardId",
					new SearchFilter("cardId", Operator.EQ, form.getCardId()));
		}
		if (form.getName() != null && !form.getName().equals("")) {
			filters.put("name",
					new SearchFilter("nama", Operator.EQ, form.getName()));
		}
		return filters;
	}

	@Override
	public CardWaste add(CardWasteForm form) {
		if (form.getCustomerId() != null && form.getCustomerId() != 0) {
			Customer customer = customerService.findById(form.getCustomerId());
			form.setCustomer(customer);
		}
		if (form.getCardId() != null && form.getCardId() != 0) {
			CreditCard creditCard = creditCardService
					.findById(form.getCardId());
			form.setCreditCard(creditCard);
		}
		
		return super.add(form);
	}

	@Override
	public CardWaste edit(CardWasteForm form) {
		if (form.getCustomerId() != null && form.getCustomerId() != 0) {
			Customer customer = customerService.findById(form.getCustomerId());
			form.setCustomer(customer);
		}
		if (form.getCardId() != null && form.getCardId() != 0) {
			CreditCard creditCard = creditCardService
					.findById(form.getCardId());
			form.setCreditCard(creditCard);
		}
		return super.edit(form);
	}

}
